<?php
/**
 * Model Actvie Record Driver - PgSQL
 *
 * @package model
 * @subpackage    activerecord
 *
 * @author jylee3@simplexi.com
 * @version 1.0
 */
class coreModelActiverecordDriverPgsql extends coreModelActiverecordDriverCommon
{
    public $sEscapeChar = '"';

    public $sLikeEscapeStr = " ESCAPE '%s' ";
    public $sLikeEscapeChr = '!';

    /**
     * The syntax to count rows is slightly different across different
     * database engines, so this string appears in each driver and is
     * used for the count_all() and count_all_results() functions.
     */
    public $sCountString = 'SELECT COUNT(*) AS ';
    public $sRandomKeyword = ' RANDOM()';

    /**
     * From Tables
     *
     * This function implicitly groups FROM tables so there is no confusion
     * about operator precedence in harmony with SQL standards
     *
     * @param    String    $sTables    Database Table Name
     *
     * @return    String
     */
    public function fromTables($sTables)
    {
        if (!is_array($sTables)) {
            $sTables = array($sTables);
        }

        return implode(', ', $sTables);
    }

    /**
     * Escape String
     *
     * @param    String    Query String
     * @param    Boolean    whether or not the string will be used in a LIKE condition
     *
     * @return    String
     */
    public function escapeStr($sStr, $bLike=false)
    {
        if (is_array($sStr)) {
            foreach ($sStr as $mKey =>$sVal) {
                $sStr[$mKey] = $this->escapeStr($sVal, $bLike);
            }

            return $sStr;
        }

        $sStr = (function_exists('pg_escape_string'))? pg_escape_string($sStr) : addslashes($sStr);

        if ($bLike===true) {
            $sStr = str_replace(array('%', '_', $this->sLikeEscapeChr),
                array($this->sLikeEscapeChr.'%', $this->sLikeEscapeChr.'_', $this->sLikeEscapeChr.$this->sLikeEscapeChr),
                $sStr);
        }

        return $sStr;
    }

    /**
     * Limit string
     *
     * Generates a platform-specific LIMIT clause
     *
     * @param    String    the sql query string
     * @param    Integer    the number of rows to limit the query to
     * @param    Integer    the offset value
     *
     * @return    String
     */
    public function limit($sSql, $iLimit, $iOffset)
    {
        $sSql .= 'LIMIT '.$iLimit;

        if ($iOffset > 0) {
            $sSql .= ' OFFSET '.$iOffset;
        }

        return $sSql;
    }
}
